package com.atguigu.gmall.common.config.executor;

import com.atguigu.gmall.common.config.executor.properties.ThreadPoolProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lfy
 * @Description
 * @create 2023-08-23 15:19
 */
@Slf4j
@EnableConfigurationProperties(ThreadPoolProperties.class) //1、开启绑定 2、组件放到容器中
@Configuration(proxyBeanMethods = false)
public class ThreadPoolExecutorAutoConfiguration {


//    @Bean
//    public ThreadPoolProperties poolProperties(){
//        return new ThreadPoolProperties();
//    }



    @Primary  //主要用这个(默认的)；  所有@Autowired的地方只要不@Qualifier("coreExecutor")精确指定就用这个默认的
    @Bean
    ThreadPoolExecutor coreExecutor(ThreadPoolProperties poolProperties) {
        /**
         * int corePoolSize,
         * int maximumPoolSize,
         * long keepAliveTime,
         * TimeUnit unit,
         * BlockingQueue<Runnable> workQueue,
         * ThreadFactory threadFactory, 默认
         * RejectedExecutionHandler handler
         */
        log.info("正在给容器中准备自定义线程池.....");
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                poolProperties.getCore(),
                poolProperties.getMax(),
                poolProperties.getKeepAliveTime(),
                poolProperties.getUnit(),
                new LinkedBlockingQueue<>(poolProperties.getWorkQueueSize()),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        return executor;
    }


    @Bean
    ThreadPoolExecutor otherExecutor(ThreadPoolProperties poolProperties) {
        /**
         * int corePoolSize,
         * int maximumPoolSize,
         * long keepAliveTime,
         * TimeUnit unit,
         * BlockingQueue<Runnable> workQueue,
         * ThreadFactory threadFactory, 默认
         * RejectedExecutionHandler handler
         */
        log.info("正在给容器中准备自定义线程池.....");
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                poolProperties.getCore(),
                poolProperties.getMax(),
                poolProperties.getKeepAliveTime(),
                poolProperties.getUnit(),
                new LinkedBlockingQueue<>(poolProperties.getWorkQueueSize()),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        return executor;
    }
}
